package com.cash.app.utils

import android.content.Context
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.android.installreferrer.api.ReferrerDetails
import com.cash.app.constant.AppConstant

object GPReferrerUtils {

    const val TAG = "GPReferrerUtils"

    // save refer, use in basic/get-channel
    fun init(context: Context) {
        val referrerClient = InstallReferrerClient.newBuilder(context).build()
        referrerClient.startConnection(object : InstallReferrerStateListener {

            override fun onInstallReferrerSetupFinished(responseCode: Int) {
                when (responseCode) {
                    InstallReferrerClient.InstallReferrerResponse.OK -> {
                        // Connection established.
                        val response: ReferrerDetails = referrerClient.installReferrer
                        val referrerUrl: String = response.installReferrer
                        TLog.i("referrer url= $referrerUrl", TAG)
                        // save referrerUrl
                        SpUtils.put(AppConstant.K_GP_REFERRER, referrerUrl)
                        // disconnect
                        referrerClient.endConnection()
                    }

                    InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
                        // API not available on the current Play Store app.
                        TLog.i("get referrer FEATURE_NOT_SUPPORTED", TAG)
                    }

                    InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
                        // Connection couldn't be established.
                        TLog.i("get referrer SERVICE_UNAVAILABLE", TAG)
                    }
                }
            }

            override fun onInstallReferrerServiceDisconnected() {
                // Try to restart the connection on the next request to
                // Google Play by calling the startConnection() method.
                TLog.i("get referrer ServiceDisconnected", TAG)
            }
        })
    }

}
